<template>
  <div class="p20 bg-white console" v-loading="loading">
    <el-form
      :model="form"
      ref="form"
      :rules="rules"
      class="mt20 overflow pl15 pr15"
      label-position="right"
    >
      <el-row>
        <el-col :span="7" class="mb15 form-inp">
          <el-form-item
            label="公告类型"
            prop="announcementType"
            :label-width="labelWidth"
          >
            <el-select
              placeholder="请选择公告类型"
              v-model="form.announcementType"
            >
              <el-option
                v-for="item in announcementTypeList"
                :key="item.number"
                :label="item.name"
                :value="item.number"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9" class="mb15 form-inp">
          <el-form-item prop="istop">
            <el-switch
              v-model="form.istop"
              active-color="#1bb49a"
              inactive-color="#dcdfe6"
              active-text="公告置顶"
            ></el-switch>
            <span class="gray">(注：公告置顶上线为3)</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="space-around">
        <el-col :span="24" class="mb15">
          <el-form-item
            label="公告标题"
            prop="title"
            :label-width="labelWidth"
            class="required"
          >
            <el-input
              v-model="form.title"
              autocomplete="off"
              placeholder="请输入公告标题"
              class="ml20"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="space-around">
        <el-col :span="24" class="mb15 form-inp">
          <el-form-item
            label="公告内容"
            prop="content"
            :label-width="labelWidth"
            class="required"
          >
            <div class="ml20">
              <RichText
                :filesObject="filesObject"
                :showImgPlugins="true"
              ></RichText>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="space-around">
        <el-col :span="24" class="mb15">
          <el-form-item
            label="状态"
            prop="status"
            :label-width="labelWidth"
            class="required"
          >
            <el-radio-group v-model="form.status" class="ml20">
              <el-radio label="撤回">撤回</el-radio>
              <el-radio label="发布中">发布中</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="space-around">
        <el-col :span="12" class="mb15">
          <el-form-item>
            <GoBack />
            <el-button
              style="width: 120px;"
              class="theme-btn"
              @click="handleEdit"
              >提 交</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import GoBack from "@/components/go_back";
import RichText from "@/components/rich_text";
import { vlength } from "@/utils/verification.js";
import { getAllDictionary } from "@/apis/dictionary";
import { editNotice, getNotice } from "@/apis/information";
import { replaceImageSrc } from "@/utils/html_RegExp_replace";
import { urlToBase64, base64ToFile } from "@/utils/data_transform";

export default {
  name: "Edit_notice",
  data() {
    return {
      form: {
        title: "",
        status: "",
        content: "",
        istop: false,
        announcementType: ""
      },
      index: 0,
      oldPhoto: [],
      filesObject: {},
      realFilesObject: {},
      labelWidth: "110px",
      announcementTypeList: [],
      rules: {
        announcementType: {
          required: true,
          message: "请选择公告类型",
          trigger: "blur"
        },
        title: {
          validator: vlength(2, 50, "请输入公告标题"),
          trigger: "blur"
        },
        status: {
          required: true,
          message: "请选择状态",
          trigger: "blur"
        }
      }
    };
  },
  computed: {
    ...mapGetters(["loading"])
  },
  mounted() {
    this.getAnnouncementTypeList();
    this.getDetailNotice(this.$route.query.id);
  },
  methods: {
    async getDetailNotice(id) {
      const { object } = await getNotice({
        communityAnnouncementId: id
      });
      tinyMCE.activeEditor.setContent(object.content);
      this.backfill(object.photos);
      object.istop = object.top === 2 ? true : false;
      this.form = object;
    },
    backfill(photos) {
      this.oldPhoto = photos.split(",");
      this.oldPhoto.forEach(item => {
        const locateFileName = item.lastIndexOf("/") + 1;
        const fileName = item.substring(locateFileName, item.length);

        urlToBase64(`${item}?t=${new Date().getTime()}`, base64 => {
          this.filesObject[item] = base64ToFile(base64, fileName);
        });
      });
    },
    async getAnnouncementTypeList() {
      const { rows } = await getAllDictionary({
        fieldName: "announcementType"
      });

      this.announcementTypeList = rows;
    },
    async handleEdit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const content = tinyMCE.activeEditor.getContent();

          if (content.length < 10) {
            return this.$notify.error({
              title: "错误",
              message: "请编辑公告内容！"
            });
          }

          const newContent = replaceImageSrc(
            this.index,
            this.filesObject,
            this.realFilesObject,
            content
          );
          const formData = new FormData();

          const realFilesObject = this.realFilesObject;
          let files = [];

          for (let key in realFilesObject) {
            formData.append("files", realFilesObject[key]);
          }

          formData.append("content", newContent);
          formData.append("title", this.form.title);
          formData.append("id", this.$route.query.id);
          formData.append("status", this.form.status);
          formData.append("top", this.form.istop === true ? "2" : "1");
          formData.append("userId", +sessionStorage.getItem("userId"));
          formData.append("announcementType", this.form.announcementType);

          this.$store.dispatch("load/setLoading", true);
          // editNotice(formData).then(res => {
          //   this.$store.dispatch("load/setLoading", false);
          //   this.$router.go(-1);
          //   this.$message({
          //     type: "success",
          //     message: res.msg
          //   });
          // });
          this.$store.dispatch("load/setLoading", false);
          this.$router.go(-1);
          this.$message({
            type: "success",
            message: "操作成功！"
          });
        }
      });
    }
  },
  components: {
    GoBack,
    RichText
  }
};
</script>

<style scoped lang="less"></style>
